<?php
/**
 * 早起打卡分钱模块微站定义
 *
 * @author
 * @url
 */
defined('IN_IA') or exit('Access Denied');
define("DAKA_PATH", '/addons/dashen_zaoqizhuanqian/');
define("IMG_DAKA_PATH", '../addons/dashen_zaoqizhuanqian/');
define("MODULE_NAME", 'dashen_zaoqizhuanqian');
class dashen_zaoqizhuanqianModuleSite extends WeModuleSite {
    var $zd_tx;
    var $zd_yj;
    var $dk_endtime;
    var $today_end;
    var $uniacid;
    var $openid;
    var $title;
    var $config;
    var $zhouqi;
    var $bili;
    var $service;
    var $xnumber;
    var $xmoney;
    var $xbili;
    var $zstate;
    var $wenzi;
    var $txsx;
    var $fdje;
    var $fstate;
    var $ysstate;
    var $tzstate;
    var $djstate;
    var $biz_id;
    var $txdemo;
    var $txbank;
    var $paychecked;
    function __construct() {
        global $_W,$_GPC;
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$_W['uniacid']);
        $others =json_decode($setting['other_setting'],true);
       // $other =json_decode($setting['other_setting'],true);
        $set =json_decode($setting['settings'],true);
        $endtime   =  !empty($set['endtime'])?$set['endtime']:8;
        $today = date('Y-m-d',time());
        $zhouqi1=!empty($others['zhouqi'])?intval($others['zhouqi']):21;
        $xuni=!empty($others['xuni'])?$others['xuni']:'0,0,10';
        $xuni1=explode(',',$xuni);
        $this->xnumber=$xuni1[0];
        $this->xmoney=$xuni1[1];
        $this->xbili=$xuni1[2];
        $this->today_end = strtotime($today)+3600*$endtime;
        $this->zhouqi =$zhouqi1;
        $this->bili =$set['bili'];
        $this->txsx =!empty($set['txsx'])?$set['txsx']:0;
        $this->fdje =!empty($set['fdje'])?$set['fdje']:0;
        $this->wenzi =$others['wenzi'];
        $this->zstate =$set['zstate'];
        $this->fstate =!empty($set['fstate'])?$set['fstate']:0;
        $this->djstate =!empty($set['djstate'])?$set['djstate']:0;
        $this->ysstate =!empty($set['ysstate'])?$set['ysstate']:0;
        $this->tzstate =!empty($set['tzstate'])?$set['tzstate']:0;
        $this->txdemo =!empty($set['txdemo'])?$set['txdemo']:'请输入支付宝账号';
        $this->txbank =!empty($set['txbank'])?$set['txbank']:'后台未设置';
        $this->paychecked =!empty($set['paychecked'])?$set['paychecked']:0;
        $this->biz_id =$set['biz_id'];
        $service=!empty($set['service'])?$set['service']:0;
        $this->service =$service;
        $this->dk_endtime = !empty($set['endtime'])?$set['endtime']:8;
        $this->zd_tx = $others['tixian'];
        $this->zd_yj = $others['yajin'];
        $this->uniacid = $_W['uniacid'];
        $this->openid = $_W['fans']['openid'];
        $this->title = $set['titles'];
        $this->config =$setting;
    }

    //获取用户头像
    function Get_header_img(){
        global $_W;
        $headimgurl = $_W['fans']['headimgurl'];
        if(empty($headimgurl)){
            $fans = mc_oauth_userinfo();
            $headimgurl = preg_replace('/\/0$/', '/96', stripslashes($fans['avatar']));
        }
        return $headimgurl;
    }

    //给粉丝发送消息
    function Send_Img_Message($openid,$pic,$src){
        $account_api = WeAccount::create();
        //任意指定一个文件上传
        $result = $account_api->uploadMedia($pic, 'image');
        $message = array(
            'touser' => $openid,
            'msgtype' => 'image',
            'image' => array('media_id' => $result['media_id']) //微信素材media_id，微擎中微信上传组件可以得到此值
        );
        $status = $account_api->sendCustomNotice($message);//调用微擎内部的函数
        if (is_error($status)) {
            $row['State'] = 202;
            $row['src'] = $src;
            $row['Msg']='海报发送失败'.$status['message'];
        }else{
            $row['State'] = 200;
            $row['src'] = $src;
            $row['Msg']='海报已发送至你的微信，请查看';
        }
        $this->logResult('发送图片'.$status);
        return $row;
    }

    //获取今天打卡总数
    function Get_total_day(){
        global $_W,$_GPC;
        $total_day = pdo_fetchcolumn('SELECT COUNT(id) FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="'.$this->openid.'"');
        return $total_day;
    }



    function DKsend($lock=''){
        global $_W,$_GPC;
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $today = date('Y-m-d',time());
        $time =  date('Y-m-d H:i:s',time());
        $acid=$_W['fans']['uid'];
        $total = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$this->uniacid. ' AND apply_data="' .$yesterday. '" AND yajin_state =1 ');
        $success = pdo_fetchall('SELECT *  FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$this->uniacid. ' AND daka_date ="' .$today.'" AND state=1 ');
        $success_count = pdo_fetchcolumn('SELECT SUM(bonus_num) FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$this->uniacid. ' AND daka_date ="' .$today.'"');
        $ptsend=0;
        $ptdemo='';
        $daymoney=pdo_get("zdaka_daymoney_record",array('acid'=>$acid,'date'=>$today));
        if($daymoney){
            $ptsend=$daymoney['money']/count($success);
            $ptdemo=',平台赞助：'.$ptsend.'元';
        }
        $total_money = 0;//要分的总钱数
        $success_money = 0;
        $kefen_money=0;//可以分的钱
        foreach ($total as $k=>$v){
            $total_money+=$v['yajin_money'];
        }
        foreach ($success as $k=>$v){
            $success_money+=$v['bonus_num'];
        }
        $kefen_money=($total_money-$success_money)*(100-$this->service)/100;
        $yinli_money=($total_money-$success_money)*$this->service/100;
        if($yinli_money>0){
            $data1 = array(
                'uniacid' => $this->uniacid,
                'money'     => $yinli_money,
                'date' => $today,
                'demo' => $today.'手续费'
            );
            pdo_insert('zdaka_yinli_record', $data1);
        }
        //var_dump($kefen_money);exit;
        $file_name = MODULE_ROOT.'/'.$this->uniacid.'/record/'.$today.'.rlc';
        $file_path = MODULE_ROOT.'/'.$this->uniacid.'/record';
        if (!file_exists($file_path)) {
            load()->func('file');
            mkdirs($file_path);
        }
        file_put_contents($file_name,"奖励金开始发放\n",FILE_APPEND);
        if($kefen_money>=0 && $success!=''){
            if($total_money<=0){
                $jl_money = 0;
            }else {
                $jl_money = ($kefen_money/$success_count);
               // $jl_money = floor($jl_money * 100) / 100;
            }
            foreach($success as $item){
                $jl_money_dan = $jl_money;//单份奖励金
//                $jl_money_count = $jl_money_dan * $item['bonus_num'];
//                $jl_money_count1 = $jl_money_dan * $jl_money_count+$item['bonus_num'];
                //更改余额
                if(strtotime($item['huikuan_date'])<=strtotime(date('Y-m-d',time()))){
                    $jl_money_count = $jl_money_dan * $item['bonus_num']+$item['bonus_num']+$ptsend;
                    $jl_money_count = floor($jl_money_count * 100) / 100;
                    pdo_update('zdaka_user',array('money +='=>$jl_money_count),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                    pdo_update('zdaka_yajin_record',array('yajin_state' => 2,'demo'=>'已经完成挑战'),array('id' => $item['yid']));
                    $demo=$today.'奖励金和当期挑战金'.$ptdemo;
                }else{
                    $jl_money_count = $jl_money_dan * $item['bonus_num']+$ptsend;
                    $jl_money_count = floor($jl_money_count * 100) / 100;
                    pdo_update('zdaka_user',array('money +='=>$jl_money_count),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                    pdo_update('zdaka_yajin_record',array('apply_data' => $today,'demo'=>'打卡成功，押金继续'),array('id' => $item['yid']));
                    $demo= $today.'获得奖励金'.$ptdemo;
                }
                //更改状态
                pdo_update('zdaka_sign_record',array('state' => 2),array('id' => $item['id']));
                //更改打卡奖励总记录
                pdo_update('zdaka_total_record',array('user_total_money +=' => $jl_money_count),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                //插入分钱记录
                $data = array(
                    'uniacid' => $item['uniacid'],
                    'uid'     => $item['uid'],
                    'openid'     => $item['openid'],
                    'nickname'  => $item['nickname'],
                    'headimgurl'  => $item['headimgurl'],
                    'grant_data' => $time,
                    'grant_date' => $today,
                    'grant_money' => $jl_money_count,
                    'bonus_num' => $item['bonus_num'],
                    'demo' => $demo
                );
                pdo_insert('zdaka_grant_record', $data);
                //记录打卡成功人的uid
                file_put_contents($file_name,"用户".$item['uid']."单份".$jl_money_dan."元 份数".$item['bonus_num']." 总额".$jl_money_count."奖励金已发放\n",FILE_APPEND);
            }
        }else{
            foreach($success as $item){

//                $jl_money_count = $jl_money_dan * $item['bonus_num'];
//                $jl_money_count1 = $jl_money_dan * $jl_money_count+$item['bonus_num'];
                //更改余额
                if(strtotime($item['huikuan_date'])<=strtotime(date('Y-m-d',time()))){
                    pdo_update('zdaka_user',array('money +='=>$item['bonus_num']+$ptsend),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                    pdo_update('zdaka_yajin_record',array('yajin_state' => 2,'demo'=>'已经完成挑战'),array('id' => $item['yid']));
                    $demo=$today.'奖励金和当期挑战金'.$ptdemo;
                }else{
                    pdo_update('zdaka_yajin_record',array('apply_data' => $today,'demo'=>'打卡成功，押金继续'),array('id' => $item['yid']));
                    $demo=$today. '获得奖励金'.$ptdemo;
                }
                //更改状态
                pdo_update('zdaka_sign_record',array('state' => 2),array('id' => $item['id']));
                //更改打卡奖励总记录
                pdo_update('zdaka_total_record',array('user_total_money +=' => 0),array('uniacid' => $item['uniacid'],'openid' => $item['openid']));
                //插入分钱记录
                $data = array(
                    'uniacid' => $item['uniacid'],
                    'uid'     => $item['uid'],
                    'openid'     => $item['openid'],
                    'nickname'  => $item['nickname'],
                    'headimgurl'  => $item['headimgurl'],
                    'grant_data' => $time,
                    'grant_date' => $today,
                    'grant_money' => 0,
                    'bonus_num' => $item['bonus_num'],
                    'demo' => $demo
                );
                pdo_insert('zdaka_grant_record', $data);
                //记录打卡成功人的uid
                file_put_contents($file_name,"用户".$item['uid']."单份0元 份数".$item['bonus_num']." 总额0奖励金已发放\n",FILE_APPEND);
            }
        }
        //修改打卡失败用户的押金状态
        pdo_update('zdaka_yajin_record',array('yajin_state' => 0,'demo'=>'未打卡','Invaliddate' => $today,'updata_date'=>$today,'bonus_num'=>0),array('uniacid' => $this->uniacid,'yajin_state' => 1,'daka_date !='=>$today,'updata_date'=>'0000-00-00','apply_data'=>$yesterday,'yajin_data <'=>date('Y-m-d H:i:s',$this->today_end)));
        file_put_contents($file_name,"奖励金发放结束\n",FILE_APPEND);
		if(!empty($lock)){
			//执行完成解锁
			flock($lock,LOCK_UN);		
		}		
    }

    /**
     * 判断是否SSL协议
     * @return boolean
     */
    function is_ssl() {
        if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
            return true;
        }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
            return true;
        }
        return false;
    }

    public function doWebPtrecord() {
        global $_GPC,$_W;
        $action = $_GPC['action']?$_GPC['action']:'';
        $zhichu1=0;$shouyi1=0;
        $uniacid=$this->uniacid;
        $acid=$this->uniacid;
        $zhichu = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yinli_record') . ' WHERE uniacid ='.$this->uniacid.' and state = 1' );
        $shouyi = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yinli_record') . ' WHERE uniacid ='.$this->uniacid.' and  state = 0' );
        $pagesize=15;
        $pageindex =max(1,intval($_GPC['page']));
        $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_yinli_record")."where uniacid = {$uniacid}"));
        $pager = pagination($total, $pageindex, $pagesize);
        $p = ($pageindex-1) * $pagesize;
        $zong= pdo_fetchall("SELECT * FROM ".tablename("zdaka_yinli_record")." where uniacid = {$uniacid} ORDER BY date desc LIMIT ".$p.",".$pagesize);
        foreach ($zhichu as $k=>$v){
            $zhichu1 += $v['money'];
        }
        foreach ($shouyi as $k=>$v){
            $shouyi1 += $v['money'];
        }

        if($action=='list'){
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_daymoney_record")." where acid = {$acid}"  ));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_daymoney_record")."where acid = {$acid}  ORDER BY date desc LIMIT ".$p.",".$pagesize);
        }
        if($action=='add'){
            if($_GPC['id']!=''){
                $res=pdo_get('zdaka_daymoney_record',array('id'=>$_GPC['id'],'acid'=>$acid));
            }
            if($_W['ispost']){
                $data = $_POST;
                $data['acid'] = $acid;
                if($_GPC['id']==''){
                    pdo_insert('zdaka_daymoney_record',$data,array('acid' => $acid));
                    message('添加成功' ,$this->createWebUrl('ptrecord',array('action'=>'list')),'success');
                }else{
                    pdo_update('zdaka_daymoney_record',$data,array('acid' => $acid,'id'=>$_GPC['id']));
                    message('修改成功' ,$this->createWebUrl('ptrecord',array('action'=>'list')),'success');
                }

            }


        }

        if($action=='delete'){
            pdo_delete('zdaka_daymoney_record',array('id'=>$_GPC['id'],'acid'=>$acid));
            message('删除成功' ,$this->createWebUrl('ptrecord',array('action'=>'list')),'success');
        }



        include $this->template('ptrecord');
    }
    public function doWebUser() {
        global $_GPC,$_W;
        $action = $_GPC['action']?$_GPC['action']:'';
        $acid=$_W['account']['acid'];
        $uid=$_GPC['uid'];
        $nickname=$_GPC['nickname'];
        if($action==''){
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_user")."where uniacid = {$acid}"));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            if($uid){
                $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_user")." where uniacid = {$acid} and uid = {$_GPC['uid']}");
            }elseif($nickname){
                $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_user")." where uniacid = {$acid} and nickname like '%{$nickname}%'");
            }else{
                $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_user")." where uniacid = {$acid} ORDER BY id LIMIT ".$p.",".$pagesize);
            }
            
        }
        if($action=='up_user'){
            if($_GPC['state1']=='1'){
                $row = pdo_update("zdaka_user",array('state'=>0),array('id' => $_GPC['id']));
                message("取消成功", $this->createWebUrl('user', array('action' => '')), "success");exit;
            }else{
                $row = pdo_update("zdaka_user",array('state'=>1),array('id' => $_GPC['id']));
                message("拉黑成功", $this->createWebUrl('user', array('action' => '')), "success");
            }

        }
        if($action=='add'){
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_pay_record")." where uniacid = {$acid} and openid = '".$_GPC['openid']."' and state =1 "));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_pay_record")." where uniacid = {$acid} and openid = '".$_GPC['openid']."' and state =1 ORDER BY id LIMIT ".$p.",".$pagesize);
            foreach ($res as $k=>$v){
                $res[$k]['user']=pdo_get('zdaka_user',array('openid'=>$v['openid']));
            }

        }
        if($action=='yqlb'){
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_user")." where fuid =" .$_GPC['uid'] ));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_user")."where uniacid = {$acid} and fuid = " .$_GPC['uid']."  ORDER BY id LIMIT ".$p.",".$pagesize);


        }

        if($action=='zuijin'){
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_pay_record")." where uniacid = {$acid} and state =1 "));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_pay_record")." where uniacid = {$acid} and state =1 ORDER BY id desc LIMIT ".$p.",".$pagesize);
            foreach ($res as $k=>$v){
                $res[$k]['user']=pdo_get('zdaka_user',array('openid'=>$v['openid']));
            }

        }

        include $this->template('user');


    }
    public function doWebIncome() {
        global $_GPC,$_W;
        $action = $_GPC['action']?$_GPC['action']:'';
        $acid=$_W['account']['acid'];
        if($action==''){
            $shou = pdo_fetchcolumn("SELECT SUM(fee) FROM " . tablename("zdaka_pay_record")  ." where uniacid = {$acid} and state =1 ");
            $zhi = pdo_fetchcolumn('SELECT SUM(tixian_money) FROM ' . tablename('zdaka_tixian_record') ." where uniacid = {$acid} and tixian_state =1 ");
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_pay_record")." where uniacid = {$acid} and state =1 "));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_pay_record")." where uniacid = {$acid}  and state =1 ORDER BY id LIMIT ".$p.",".$pagesize);
            foreach ($res as $k=>$v){
                $res[$k]['user']=pdo_get('zdaka_user',array('openid'=>$v['openid']));
            }

        }
        if($action=='tixian'){
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_tixian_record")." where uniacid = {$acid} and tixian_state =1 "));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_tixian_record")." where uniacid = {$acid} and tixian_state =1 ORDER BY id LIMIT ".$p.",".$pagesize);

        }


        include $this->template('income');


    }
    public function doWebList() {
        global $_GPC,$_W;
        $action = $_GPC['action']?$_GPC['action']:'';
        $acid=$_W['account']['acid'];
        if($action==''){
            $res=pdo_getall('zdaka_list',array('acid'=>$acid));

        }
        if($action=='add'){
            if($_GPC['id']!=''){
                $res=pdo_get('zdaka_list',array('id'=>$_GPC['id'],'acid'=>$acid));

            }
            if($_W['ispost']){
                $data = $_POST;
                $data['acid'] = $acid;
                if($_GPC['id']==''){
                    pdo_insert('zdaka_list',$data,array('acid' => $acid));
                    message('添加成功' ,$this->createWebUrl('list',array('action'=>'')),'success');
                }else{
                    pdo_update('zdaka_list',$data,array('acid' => $acid,'id'=>$_GPC['id']));
                    message('修改成功' ,$this->createWebUrl('list',array('action'=>'')),'success');
                }

            }


        }
        if($action=='delete'){
            pdo_delete('zdaka_list',array('id'=>$_GPC['id'],'acid' => $acid));
            message('删除成功' ,$this->createWebUrl('list',array('action'=>'')),'success');

        }


        include $this->template('list');


    }


    public function doWebNotice() {
        global $_GPC,$_W;
        $action = $_GPC['action']?$_GPC['action']:'';
        $acid=$_W['account']['acid'];
        $pagesize=10;
        $pageindex =max(1,intval($_GPC['page']));
        $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_notice_record")." where acid = {$acid}  "));
        $pager = pagination($total, $pageindex, $pagesize);
        $p = ($pageindex-1) * $pagesize;
        $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_notice_record")." where acid = {$acid} ORDER BY id LIMIT ".$p.",".$pagesize);
        if($action=='add'){
            if($_GPC['id']!=''){
                $res=pdo_get('zdaka_notice_record',array('id'=>$_GPC['id'],'acid'=>$acid));
            }
            if($_W['ispost']){
                $data = $_POST;
                $data['time'] = date('Y-m-d H:i:s');
                $data['acid'] = $acid;
                if($_GPC['id']==''){
                    pdo_insert('zdaka_notice_record',$data,array('acid' => $acid));
                    message('添加成功' ,$this->createWebUrl('notice',array('action'=>'')),'success');
                }else{
                    pdo_update('zdaka_notice_record',$data,array('acid' => $acid,'id'=>$_GPC['id']));
                    message('修改成功' ,$this->createWebUrl('notice',array('action'=>'')),'success');
                }

            }


        }
        if($action=='delete'){
            pdo_delete('zdaka_notice_record',array('id'=>$_GPC['id'],'acid' => $acid));
            message('删除成功' ,$this->createWebUrl('notice',array('action'=>'')),'success');

        }

        if($action=='show'){
            $aa=pdo_update('zdaka_notice_record',array('state'=>$_POST['state']),array('id'=>$_POST['id'],'acid' => $acid));
            echo $aa;exit;

        }
        include $this->template('notice');


    }

    public function doWebCard() {
        global $_GPC,$_W;
        $action = $_GPC['action']?$_GPC['action']:'';
        $acid=$_W['account']['acid'];
        $pagesize=10;
        $pageindex =max(1,intval($_GPC['page']));
        $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_card")." where acid = {$acid}  "));
        $pager = pagination($total, $pageindex, $pagesize);
        $p = ($pageindex-1) * $pagesize;
        $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_card")." where acid = {$acid} ORDER BY id LIMIT ".$p.",".$pagesize);
        if($action=='add'){
            if($_GPC['id']!=''){
                $res=pdo_get('zdaka_care',array('id'=>$_GPC['id'],'acid'=>$acid));
            }
            if($_W['ispost']){
                $data = $_POST;
                $data['time'] = date('Y-m-d H:i:s');
                $data['acid'] = $acid;
                if($_GPC['id']==''){
                    pdo_insert('zdaka_card',$data,array('acid' => $acid));
                    message('添加成功' ,$this->createWebUrl('card',array('action'=>'')),'success');
                }else{
                    pdo_update('zdaka_card',$data,array('acid' => $acid,'id'=>$_GPC['id']));
                    message('修改成功' ,$this->createWebUrl('card',array('action'=>'')),'success');
                }

            }


        }
        if($action=='delete'){
            pdo_delete('zdaka_notice_record',array('id'=>$_GPC['id'],'acid' => $acid));
            message('删除成功' ,$this->createWebUrl('notice',array('action'=>'')),'success');

        }

        if($action=='show'){
            $aa=pdo_update('zdaka_notice_record',array('state'=>$_POST['state']),array('id'=>$_POST['id'],'acid' => $acid));
            echo $aa;exit;

        }
        include $this->template('notice');


    }


    public function doWebPunch() {//后端今日现状
        global $_GPC,$_W;
        $action = $_GPC['action']?$_GPC['action']:'';
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $today = date('Y-m-d',time());
        $time =  date('Y-m-d H:i:s',time());
        $acid=$this->uniacid;
        $total = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$this->uniacid. ' AND apply_data="' .$yesterday. '" AND yajin_state =1 ');
        $success = pdo_fetchall('SELECT *  FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$this->uniacid. ' AND daka_date ="' .$today.'" AND state=1 ');
        $success_count = pdo_fetchcolumn('SELECT SUM(bonus_num) FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$this->uniacid. ' AND daka_date ="' .$today.'"');
        $total_money = 0;//要分的总钱数
        $success_money = 0;
        $kefen_money=0;//可以分的钱
        foreach ($total as $k=>$v){
            $total_money+=$v['yajin_money'];
        }
        foreach ($success as $k=>$v){
            $success_money+=$v['bonus_num'];
        }
        $kefen_money=($total_money-$success_money)*(100-$this->service)/100;
        $yinli_money=($total_money-$success_money)*$this->service/100;
        $jl_money = ($kefen_money/$success_count);

        if($action==''){
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_sign_record")."where uniacid = {$acid} AND daka_date = '".$today."'"));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            $res = pdo_fetchall("SELECT *  FROM ". tablename("zdaka_sign_record") . " WHERE uniacid = {$acid} AND daka_date = '".$today."'ORDER BY id LIMIT ".$p.",".$pagesize);

        }
        if($action=='fail'){
            $pagesize=10;
            $pageindex =max(1,intval($_GPC['page']));
            $total = count(pdo_fetchall("SELECT * FROM ".tablename("zdaka_yajin_record")." where uniacid = {$acid} and daka_date != '".$today."' and apply_data='".$yesterday."' and   yajin_state =1 "));
            $pager = pagination($total, $pageindex, $pagesize);
            $p = ($pageindex-1) * $pagesize;
            $res = pdo_fetchall("SELECT * FROM ".tablename("zdaka_yajin_record")." where uniacid = {$acid} and daka_date != '".$today."' and yajin_state =1  and apply_data='".$yesterday."' ORDER BY id LIMIT ".$p.",".$pagesize);
        }
        if($action=='sign'){
            $uniacid=$this->uniacid;
            $yajin=pdo_get('zdaka_yajin_record',array('id'=>$_GPC['id']));
            $post = array(
                'uniacid' => $this->uniacid,
                'uid' =>  $yajin['uid'],
                'openid' => $yajin['openid'],
                'nickname' => $yajin['nickname'],
                'headimgurl' =>$yajin['headimgurl'],
                'daka_date' => $today,
                'daka_datatime' => $time,
                'huikuan_date' => $yajin['huikuan_date'],
                'bonus_num' => $yajin['yajin_money'],
                'yid' => $yajin['id'],
            );
            pdo_insert('zdaka_sign_record', $post);
            //更改押金表中打卡状态为已打卡
            pdo_update('zdaka_yajin_record',array('is_daka' => 1,'daka_date'=>$today),array('id' => $_GPC['id']));

            //查询记录天数表中是否有记录
            $sql = 'SELECT *  FROM ' . tablename('zdaka_total_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$yajin['openid'].'"';
            $rel  = pdo_fetchall($sql);
            if($rel){
                //查询昨天是否打卡，如果打卡打卡填上累加，如果没打卡，打卡天数从新计算
                $sql1 = 'SELECT *  FROM ' . tablename('zdaka_total_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$yajin['openid']. '" AND last_sign_date = "'.$yesterday.'"';
                $result = pdo_fetchall($sql1);
                if($result){
                    $data = array(
                        'uniacid' => $this->uniacid,
                        'uid' =>  $yajin['uid'],
                        'openid' =>  $yajin['openid'],
                        'headimgurl' =>  $yajin['headimgurl'],
                        'nickname' =>  $yajin['nickname'],
                        'last_sign_date' => $today,
                        'last_sign_time' => $time,
                        'user_total_score' => $result['0']['user_total_score']+1,
                    );
                    pdo_update('zdaka_total_record', $data,array('uniacid' => $this->uniacid, 'openid' => $yajin['openid']));
                }
                else{
                    $data = array(
                        'uniacid' => $this->uniacid,
                        'uid' =>  $yajin['uid'],
                        'openid' =>  $yajin['openid'],
                        'headimgurl' =>  $yajin['headimgurl'],
                        'nickname' => $yajin['nickname'],
                        'last_sign_date' => $today,
                        'last_sign_time' => $time,
                        'user_total_score' => 1,
                    );
                    pdo_update('zdaka_total_record', $data,array('uniacid' => $this->uniacid, 'openid' => $yajin['openid']));
                }
            }
            else{
                $data = array(
                    'uniacid' => $this->uniacid,
                    'uid' =>  $yajin['uid'],
                    'openid' =>  $yajin['openid'],
                    'headimgurl' => $yajin['headimgurl'],
                    'nickname' => $yajin['nickname'],
                    'last_sign_date' => $today,
                    'last_sign_time' => $time,
                    'user_total_score' =>1,
                );
                pdo_insert('zdaka_total_record', $data);
            }

        }
        include $this->template('punch');


    }

    public function doWebSetting() {
        //这个操作被定义用来呈现 管理中心导航菜单
        //后台设置
        global $_W,$_GPC;
        $today = date('Y-m-d',time());
        $is_daka = pdo_fetchcolumn("select COUNT(id) FROM ".tablename('zdaka_sign_record')." where uniacid = {$_W['uniacid']} AND daka_date='$today'");
        $setting = pdo_fetch("select * from ".tablename('zdaka_config')." where uniacid = {$_W['uniacid']}");
        $set =  json_decode($setting['settings'],true);
        $sip =$_SERVER["REMOTE_ADDR"];
        $url1= ATTACHMENT_ROOT.$_W['uniacid']."/".MODULE_NAME;

        if(checksubmit()){
            //$this-> CheckAuthorization();
            $aa=explode(':',$_GPC['endtime']);
            $endtime=$aa[0]+($aa[1]/60);
            $bb=explode(':',$_GPC['starttime']);
            $starttime=$bb[0]+($bb[1]/60);
            $paychecked='0';
            if($_POST['paychecked']){
                $paychecked=implode('',$_POST['paychecked']);
            }

            $d=array(
                'uniacid'=>$_W['uniacid'],
                'appid'=>trim($_GPC['appid']),
                'titles'=>trim($_GPC['titles']),
                'appsecret'=>trim($_GPC['appsecret']),
                'mch_id'=>trim($_GPC['mch_id']),
                'partnerkey'=>trim($_GPC['partnerkey']),
                'ip'=>trim($_GPC['ip']),
                'starttime'=>trim($starttime),
                'endtime'=>trim($endtime),
                'service'=>trim($_GPC['service']),
                'txsx'=>trim($_GPC['txsx']),
                'fdje'=>trim($_GPC['fdje']),
                'bili'=>trim($_GPC['bili']),
                'fstate'=>$_POST['fstate'],
                'ysstate'=>$_POST['ysstate'],
                'tzstate'=>$_POST['tzstate'],
                'zstate'=>$_POST['zstate'],
                'djstate'=>$_POST['djstate'],
                'nostate'=>$_POST['nostate'],
                'txdemo'=>$_POST['txdemo'],
                'txbank'=>$_POST['txbank'],
                'paychecked'=>$paychecked,
                'biz_id'=>$_POST['biz_id'],
                'user_openid'=>trim($_GPC['user_openid']),
            );
            $jsonStr = json_encode($d);
            $data = array(
                'uniacid' => $_W['uniacid'],
                'settings' =>$jsonStr,
            );
            if(!$setting){
                pdo_insert('zdaka_config', $data);
            }
            else{
                pdo_update('zdaka_config', array('settings' =>$jsonStr),array('uniacid' => $_W['uniacid']));
            }
            $settings['rootca'] = trim($_GPC['rootca']);
            $settings['cert']   = trim($_GPC['cert']);
            $settings['key']    = trim($_GPC['key']);

            load()->func('file');
            mkdirs(ATTACHMENT_ROOT.MODULE_NAME."/".$_W['uniacid']);
            $url1 = ATTACHMENT_ROOT.MODULE_NAME."/".$_W['uniacid'];

            if($settings['rootca'] !=''){
                file_put_contents($url1."/rootca.pem",$settings['rootca']);
            }
            if($settings['cert'] !=''){
                file_put_contents($url1.'/cert.pem',$settings['cert']);
            }
            if($settings['key'] !=''){
                file_put_contents($url1.'/key.pem',$settings['key']);
            }
            message('操作成功',referer(),'success');
        }
        include $this->template('setting');
    }

    /*	public function doWebClearData() {
            //这个操作被定义用来呈现 管理中心导航菜单
            //清空测试数据
            global $_W,$_GPC;

            pdo_query("TRUNCATE TABLE ".tablename('zdaka_grant_record'));
            pdo_query("TRUNCATE TABLE ".tablename('zdaka_sign_record'));
            pdo_query("TRUNCATE TABLE ".tablename('zdaka_tixian_record'));
            pdo_query("TRUNCATE TABLE ".tablename('zdaka_total_record'));
            pdo_query("TRUNCATE TABLE ".tablename('zdaka_user'));
            pdo_query("TRUNCATE TABLE ".tablename('zdaka_yajin_record'));
            pdo_query("TRUNCATE TABLE ".tablename('zdaka_yaoqing_record'));
            message('清除测试数据成功', $this->createWebUrl('setting'), 'success');
        }*/
    public function doWebTxrecord() {
        //这个操作被定义用来呈现 提现记录导航菜单
        global $_W,$_GPC;
        $condition=' WHERE uniacid ='.$this->uniacid;

        if (!empty($_GPC['date'])) {
            $date = trim($_GPC['date']);
            $condition .= " AND tixian_data between '$date 00:00:00' and '$date 23:59:59' ";
        }
        if (!empty($_GPC['tx_state'])) {
            $tx_state = trim($_GPC['tx_state']);
            $condition .= " AND tixian_state = '$tx_state' ";
        }
        if (!empty($_GPC['nickname'])) {
            $nickname = trim($_GPC['nickname']);
            $condition .= " AND nickname = '$nickname' ";
        }

        $total = pdo_fetchcolumn('SELECT COUNT(id) FROM ' . tablename('zdaka_tixian_record') . $condition);

        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 15;
        $pager = pagination($total, $pageindex, $pagesize);
        $p = ($pageindex-1) * $pagesize;
        $sql = 'SELECT *  FROM ' . tablename('zdaka_tixian_record') . $condition. '  ORDER BY `tixian_data` DESC LIMIT ' . $p . "," . $pagesize;
        $list  = pdo_fetchall($sql);
        include $this->template('txrecord');

    }

    public function doWebDkrecord() {
        //这个操作被定义用来呈现 打卡记录导航菜单
        global $_W,$_GPC;

        $today = date('Y-m-d',time());
        $dkdate = trim($_GPC['dkdate'])==''?$today:trim($_GPC['dkdate']);
        //$condition=' WHERE uniacid ='.$this->uniacid. '  AND daka_date ="'.$dkdate.'" ';

        $condition=' WHERE uniacid ='.$this->uniacid. '  AND daka_datatime >="'.$_GPC['stime'].'"  and daka_datatime <="'.$_GPC['etime'].'"';

        if (!empty($_GPC['username'])){

            $condition.='and nickname like  "%'.$_GPC['username'].'%"';
        }
        $nickname=$_GPC['username'];
        $today = date('Y-m-d',time());
        $total = pdo_fetchcolumn('SELECT COUNT(id) FROM ' . tablename('zdaka_sign_record') .$condition );
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 15;
        $pager = pagination($total, $pageindex, $pagesize);
        $p = ($pageindex-1) * 15;
        $sql = 'SELECT *  FROM ' . tablename('zdaka_sign_record') .$condition.' ORDER BY `daka_datatime` DESC LIMIT ' . $p . ',' . $pagesize;
        $list  = pdo_fetchall($sql);
//        echo "<pre>";
//        var_dump($list);die;
        include $this->template('dkrecord');

    }

    public function doWebYjrecord() {
        //这个操作被定义用来呈现 打卡记录导航菜单
        global $_W,$_GPC;

        $condition=' WHERE uniacid ='.$this->uniacid;

        if (!empty($_GPC['date'])) {
            $date = trim($_GPC['date']);
            $condition .= " AND apply_data = '$date' ";
        }
        if (!empty($_GPC['yj_state'])) {
            $ya_state = $yj_state = trim($_GPC['yj_state']);
            if($yj_state==2){
                $yj_state=0;
            }
            $condition .= " AND yajin_state = '$yj_state' ";
        }
        if (!empty($_GPC['nickname'])) {
            $nickname = trim($_GPC['nickname']);
            $condition .= " AND nickname = '$nickname' ";
        }

        $total = pdo_fetchcolumn('SELECT COUNT(id) FROM ' . tablename('zdaka_yajin_record') . $condition);
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 15;
        $pager = pagination($total, $pageindex, $pagesize);
        $p = ($pageindex-1) * 15;
        $sql = 'SELECT *  FROM ' . tablename('zdaka_yajin_record') . $condition. ' ORDER BY `yajin_data` DESC LIMIT ' . $p . "," . $pagesize;
        $list  = pdo_fetchall($sql);
        include $this->template('yjrecord');

    }

    public function doWebYqxrecord() {
        //这个操作被定义用来呈现 提现记录导航菜单
        global $_W,$_GPC;
        $uid = intval(trim($_GPC['uid']));
        $condition=' WHERE y.uniacid ='.$this->uniacid.' AND y.fuid = '.$uid;
        if (!empty($_GPC['follow_state'])) {
            $gz_state = $follow_state = trim($_GPC['follow_state']);
            if($follow_state==2){
                $follow_state = 0;
            }
            $condition .= " AND y.follow_state = '$follow_state' ";
        }

        $total = pdo_fetchcolumn('SELECT COUNT(1) FROM ' . tablename('zdaka_yaoqing_record').' as y left join ' . tablename('zdaka_user').' as u on y.openid = u.openid '.$condition);
        $pageindex = max(1, intval($_GPC['page']));
        $pagesize = 15;
        $pager = pagination($total, $pageindex, $pagesize);
        $p = ($pageindex-1) * 15;
        $sql = 'SELECT u.openid,u.nickname,u.headimgurl,u.uid,y.yaoqing_data,y.follow_state,y.fllow_count FROM ' . tablename('zdaka_yaoqing_record') .' as y left join ' . tablename('zdaka_user').' as u on y.openid = u.openid '. $condition. '  ORDER BY y.yaoqing_data DESC LIMIT ' . $p . "," . $pagesize;
        $list  = pdo_fetchall($sql);
        include $this->template('yqx_record');
    }
    public function doWebYqrecord() {
        //这个操作被定义用来呈现 提现记录导航菜单
        global $_W,$_GPC;

        $list = pdo_fetchall('SELECT count(fuid) as shu ,fuid FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' and  fuid != 0 group by fuid ' );
        foreach($list as $k=>$item){
            $list[$k]['user'] = pdo_get('zdaka_user',array('uid'=>$item['fuid']));
        }
        include $this->template('yqrecord');
    }


    public function doMobileSend(){
        //这个操作被定义用来呈现手动发放奖励金
        global $_W,$_GPC;
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $uniacid = $this->uniacid;
        $today_8 = strtotime($today)+3600*$this->dk_endtime;
        if(strtotime($time)>$today_8){
            $file_name = MODULE_ROOT.'/'.$this->uniacid.'/record/'.$today.'.rlc';
            if(!file_exists($file_name)){
                $this->DKsend();
                message($time.'发放成功！', $this->createMobileUrl('Index'), 'success');
            }
            else{
                message($time.'今天奖励金已发放，请勿重复发放！', $this->createMobileUrl('Index'), 'error');
            }
        }
        else{
            message($time.'未到发放奖励金时间！', $this->createMobileUrl('Index'), 'error');

        }
    }

    public function doMobileTixian(){
        //这个操作被定义用来呈现手动发放奖励金
        global $_W,$_GPC;
        $uniacid = $this->uniacid;
        $time = strtotime(date('Y-m-d H:i:s'));
        $user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="' .$this->openid.'"');

        if($user['money'] < $this->zd_tx){
            message('提现金额不能少于'.$this->zd_tx.'元！', $this->createMobileUrl('index'), 'error');
            exit;
        }
        $data = array(
            'uniacid' => $user['uniacid'],
            'uid' =>$user['uid'],
            'openid' => $user['openid'],
            'headimgurl' =>$user['headimgurl'],
            'nickname' => $user['nickname'],
            'tixian_data' =>date('Y-m-d H:i:s',time()),
            'tixian_money' => $user['money']*(100-$this->txsx)/100,
            'ymoney'=>$user['money'],
            'zhanghao' => $_GPC['zhanghao'],
            'name' => $_GPC['name'],
            'bank'=>$_GPC['bank'],
            'kbank'=>$_GPC['kbank'],
            'tixian_state' =>0
        );
        $res= pdo_insert('zdaka_tixian_record', $data);

        if($res){
            pdo_update('zdaka_user', array('money ' =>0),array('id' => $user['id']));
            message('已申请，请随时注意通知', $this->createMobileUrl('tixianrecord'), 'success');exit;
        }else{
            message('申请失败', $this->createMobileUrl('tixianrecord'), 'error');exit;
        }

    }

    public function doWebTixians() {
       $res= pdo_update('zdaka_tixian_record',array('tixian_state'=>1),array('id'=>$_POST['id']));
        echo $res;
    }
    public function doWebTui() {
        $res=pdo_get('zdaka_tixian_record',array('id'=>$_POST['id']));
        if($res['ymoney']>0){
            $money=$res['ymoney'];
        }else{
            $money=$res['tixian_money']/(100-$this->txsx)/100;
        }
        pdo_update('zdaka_user',array('money +='=>$money),array('openid'=>$res['openid']));
        pdo_update('zdaka_tixian_record',array('tixian_state'=>2,'demo'=>'管理员退回到余额'),array('id'=>$_POST['id']));
        echo 1;exit;
    }
    public function doWebTixian1() {
        $time = strtotime(date('Y-m-d H:i:s'));
        $tixian=pdo_get('zdaka_tixian_record',array('id'=>$_POST['id'],'tixian_state !='=>1));
        if(!$tixian){
            echo 2;exit;
        }
        $setting = pdo_fetch("select * from ".tablename('zdaka_config')." where uniacid =".$this->uniacid);
        $set =  json_decode($setting['settings'],true);
        $openid  = $tixian['openid'];
        $tx_money = $tixian['tixian_money']*100;
        //发放单号
        $fafang_number = $tixian['uid'].$time;
        $pars = array();
        $pars['mch_appid'] =$set['appid'];
        $pars['mchid'] = $set['mch_id'];
        //产生随机字符串
        $pars['nonce_str'] = $this->createNoncestr();
        // 商户订单号
        $pars['partner_trade_no'] = $fafang_number;
        // 用户openid
        $pars['openid'] =$openid;
        // 校验用户姓名选项
        $pars['check_name'] = "NO_CHECK";
        // 企业付款金额  单位为分
        $pars['amount'] =$tx_money;
        // 企业付款描述信息
        $pars['desc'] = '提现到账';
        // 调用接口的机器IP地址  自定义
        $pars['spbill_create_ip'] =$_SERVER["REMOTE_ADDR"];
        //生成签名
        $pars['sign'] =$this->getSign($pars);
        $xml = $this->createXml($pars);
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $response = $this->curl_post_ssl($url, $xml);
        if( !empty($response) ) {
            $data = simplexml_load_string($response, null, LIBXML_NOCDATA);
            $jsonStr = json_encode($data);
            $jsonArray = json_decode($jsonStr,true);
            //微信交易单号
            $jiaoyi_number = $jsonArray['payment_no'];
            $jiaoyi_time = strtotime($jsonArray['payment_time']);
            if($jsonArray['result_code']=='SUCCESS'){
                pdo_update('zdaka_tixian_record',array('tixian_state'=>1),array('id'=>$_POST['id']));
                echo 1;exit;
            }else{
                echo  $response;exit;
            }
        }else{
            //message($jsonArray['err_code_des'], $this->createMobileUrl('index'), 'error');
            echo json_encode( array('return_code' => 'FAIL', 'return_msg' => 'transfers_接口出错', 'return_ext' => array()));
        }

    }

    /**
     * 生成请求xml数据
     * @return string
     */
    function createXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            $xml.="<".$key.">".$val."</".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    /**
     *  作用：产生随机字符串，不长于32位
     */
    function createNoncestr( $length = 32 )
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    /**
     *  作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }

    /**
     *  作用：生成签名
     */
    function getSign($Obj)
    {
        foreach ($Obj as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);

        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        global $_W,$_GPC;
        $uniacid =  $this->uniacid;

        $setting = pdo_fetch("select * from ".tablename('zdaka_config')." where uniacid = {$uniacid}");

        $set =  json_decode($setting['settings'],true);
        $String = $String."&key=".$set['partnerkey'];
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;


    }

    function curl_post_ssl($url, $vars, $second=30,$aHeader=array()){
        global $_W,$_GPC;
        $url1 = ATTACHMENT_ROOT.MODULE_NAME."/".$this->uniacid;
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);

        //以下两种方式需选择一种

        //第一种方法，cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT,$url1.'/cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY,$url1.'/key.pem');

        //第二种方式，两个文件合成一个.pem文件
        //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');

        if( count($aHeader) >= 1 ){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch,CURLOPT_POST, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
        $data = curl_exec($ch);

        if($data){
            curl_close($ch);
            return $data;
        }
        else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }




    public function doWebDksetting() {
        //这个操作被定义用来呈现 管理中心导航菜单
        //后台设置
        global $_W,$_GPC;

        $is_yajin = pdo_fetchcolumn("select COUNT(id) FROM ".tablename('zdaka_yajin_record')." where uniacid = {$_W['uniacid']} AND yajin_state=1");

        $setting = pdo_fetch("select * from ".tablename('zdaka_config')." where uniacid = {$_W['uniacid']}");
        $set =  json_decode($setting['other_setting'],true);
        $set['images']=$set['images']?explode(',',$set['images']):"";
        if(checksubmit()){
            //$this-> CheckAuthorization();
            $bl_flag = $this->is_ssl();
            $http = $bl_flag?'https://':'http://';
            $pic_src = '';
            $yd_pic='';
            $er_pic='';
            if(trim($_GPC['pic'])!=''){
                if(strpos(trim($_GPC['pic']),'http') !== false){
                    $pic_src = trim($_GPC['pic']);
                }
                else{
                    $pic_src = $http.$_SERVER['HTTP_HOST']."/attachment/".trim($_GPC['pic']);
                }
            }
            if(trim($_GPC['yd_pic'])!=''){
                if(strpos(trim($_GPC['yd_pic']),'http') !== false){
                    $yd_pic = trim($_GPC['yd_pic']);
                }
                else{
                    $yd_pic = $http.$_SERVER['HTTP_HOST']."/attachment/".trim($_GPC['yd_pic']);
                }
            }
            if(trim($_GPC['er_pic'])!=''){
                if(strpos(trim($_GPC['er_pic']),'http') !== false){
                    $er_pic = trim($_GPC['er_pic']);
                }
                else{
                    $er_pic = $http.$_SERVER['HTTP_HOST']."/attachment/".trim($_GPC['er_pic']);
                }
            }

            $d=array(
                'tixian'=>trim($_GPC['tixian']),
                'yajin'=>trim($_GPC['yajin']),
                'zyajin'=>trim($_GPC['zyajin']),
                'xuni'=>trim($_GPC['xuni']),
                'zhouqi'=>trim($_GPC['zhouqi']),
                'tiaozhan'=>trim($_GPC['tiaozhan']),
                'hb_bg'=>trim($_GPC['hb_bg']),
                'wenben'=>$_GPC['wenben'],
                'wenzi'=>$_GPC['wenzi'],
                'pic'=>$pic_src,
                'images'=>$_POST['images']?implode(',',$_POST['images']):"",
                'yd_pic'=>$yd_pic,
                'er_pic'=>$er_pic,
                'ad_url'=>trim($_GPC['ad_url'])
            );
            $jsonStr = json_encode($d);
            $data = array(
                'uniacid' => $_W['uniacid'],
                'other_setting' =>$jsonStr,
            );

            if(!$setting){
                pdo_insert('zdaka_config', $data);
            }
            else{
                pdo_update('zdaka_config', array('other_setting' =>$jsonStr),array('uniacid' => $_W['uniacid']));
            }
            message('操作成功',referer(),'success');
        }
        include $this->template('dksetting');
    }

    public function doWebPostersetting() {
        //这个操作被定义用来呈现 管理中心导航菜单
        //后台设置
        global $_W,$_GPC;

        $set = json_decode($this->config['poster_setting'],true);
        $data = json_decode($set['data'],true);

        if($_GPC['op']==""||$_GPC['op']=='poster_bg'){
            $operation = 'poster_bg';

        }
        else if($_GPC['op']=='poster_dis'){
            $operation = 'poster_dis';
        }

        if (checksubmit ()) {
            $data = array (
                'hb_bg' => $_GPC ['hb_bg'],
                'zhanji' => $_GPC ['zhanji'],
                'data' => htmlspecialchars_decode($_GPC ['data']),
            );
            $jsonStr = json_encode($data);

            if (!$this->config) {
                $d = array(
                    'uniacid' => $_W['uniacid'],
                    'poster_setting' =>$jsonStr,
                );
                pdo_insert('zdaka_config', $d);
            }
            else{
                pdo_update('zdaka_config', array('poster_setting' =>$jsonStr),array('uniacid' => $_W['uniacid']));
            }
            message('操作成功',referer(),'success');
        }

        include $this->template('postersetting');
    }

    public function doWebSharesetting() {
        //这个操作被定义用来呈现 管理中心导航菜单
        //后台设置
        global $_W,$_GPC;

        $setting = pdo_fetch("select * from ".tablename('zdaka_config')." where uniacid = {$_W['uniacid']}");
        $set =  json_decode($setting['share_setting'],true);

        if(checksubmit()){
            //$this-> CheckAuthorization();
            $bl_flag = $this->is_ssl();
            $http = $bl_flag?'https://':'http://';
            $share_pic = '';
            if(trim($_GPC['share_pic'])!=''){
                if(strpos(trim($_GPC['share_pic']),'http') !== false){
                    $share_pic = trim($_GPC['share_pic']);
                }
                else{
                    $share_pic = $http.$_SERVER['HTTP_HOST']."/attachment/".trim($_GPC['share_pic']);
                }
            }

            $d=array(
                'share_title'=>trim($_GPC['share_title']),
                'share_desc'=>trim(trim($_GPC['share_desc'])),
                'share_pic'=>$share_pic,
            );
            $jsonStr = json_encode($d);
            $data = array(
                'uniacid' => $_W['uniacid'],
                'share_setting' =>$jsonStr,
            );

            if(!$setting){
                pdo_insert('zdaka_config', $data);
            }
            else{
                pdo_update('zdaka_config', array('share_setting' =>$jsonStr),array('uniacid' => $_W['uniacid']));
            }
            message('操作成功',referer(),'success');
        }
        include $this->template('sharesetting');
    }

    public function doMobileYindao() {
        global $_W,$_GPC;
        $fid = intval($_GPC['fid']);
        $uniacid=$this->uniacid;
        if($fid!=0){
            $uid     = $_W['fans']['uid'];
            $nickname = $_W['fans']['nickname'];
            $openid =  $_W['fans']['openid'];
            $headimgurl = $this->Get_header_img();
            $time = date('Y-m-d H:i:s',time());
            $user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="' .$this->openid.'"');
            $fuser=  pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND uid =' .$fid);
            if($fuser['fuid']!=0){
                $guid=$fuser['fuid'];
            }else{
                $guid=0;
            }
            if($user=='' && $uniacid !=''){
                $data = array(
                    'guid'=>$guid,
                    'fuid' => $fid,
                    'uniacid' => $uniacid,
                    'uid'     => $uid,
                    'nickname'  => $nickname,
                    'openid'  => $openid,
                    'headimgurl'  => $headimgurl,
                    'reg_time' => $time,
                );
                $rel = pdo_insert('zdaka_user', $data);
            }else{
                if($user['nickname'] != $nickname){
                    $rel = pdo_update('zdaka_user',array('nickname' => $nickname),array('uniacid' => $uniacid,'openid' => $this->openid));
                }
                if($user['headimgurl'] != $headimgurl){
                    $rel = pdo_update('zdaka_user',array('headimgurl' => $headimgurl),array('uniacid' => $uniacid,'openid' => $this->openid));
                }
                if($user['openid'] != $openid){
                    $rel = pdo_update('zdaka_user',array('openid' => $openid),array('uniacid' => $uniacid,'openid' => $this->openid));
                }
            }

        }
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$_W['uniacid']);
        $set =json_decode($setting['other_setting'],true);
        $bg = $set['yd_pic'];
        $er = $set['er_pic'];
        if($this->biz_id){
            header("location:https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz={$this->biz_id}==&scene=110#wechat_redirect");
        }else{
            include $this->template('yindao');
        }


    }

    /**
     * 十六进制 转 RGB
     */
    function hex2rgb($hexColor) {
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3) {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else {
            $color = $hexColor;
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
        }
        return $rgb;
    }
    public function CreateImage($url){
        global $_W,$_GPC;
        $uniacid =  $this->uniacid;
        $uid     = $_W['fans']['uid'];
        //header("content-type: image/jpeg");//如果要看报什么错，可以先注释调这个header
        //海报背景
        $set = json_decode($this->config['poster_setting'],true);
        $data = json_decode($set['data'],true);
        $bg = tomedia($set['hb_bg']);
        $is_z = $set['zhanji'];
        if(empty($set['hb_bg'])){
            $bg = MODULE_ROOT."/images/yq.jpg";
        }
        $head = array();
        $qr = array();
        $nick = array();
        foreach($data as $item){
            if($item[type]=='img'){
                $head['qiyong']=1;
                $head['left']=2*$item['left'];
                $head['top']=2*$item['top'];
                $head['width']=2*$item['width'];
                $head['height']=2*$item['height'];
            }
            if($item[type]=='qr'){
                $qr['qiyong']=1;
                $qr['left']=2*$item['left'];
                $qr['top']=2*$item['top'];
                $qr['width']=2*$item['width'];
                $qr['height']=2*$item['height'];
            }
            if($item[type]=='name'){
                $nick['qiyong']=1;
                $nick['left']=2*$item['left'];
                $nick['top']=2*($item['top']+$item['height']);
                $nick['width']=$item['width'];
                $nick['height']=$item['height'];
                $nick['size']=$item['size'];
                $nick['color']=$item['color'];
            }
        }
        $bg = imagecreatefromjpeg($bg);
        ///创建和背景一样大小的真彩色画布
        $image_3 = imagecreatetruecolor(imagesx($bg),imagesy($bg));
        //为真彩色画布创建白色背景，再设置为透明
        $color = imagecolorallocate($image_3, 255, 255, 255);
        imagefill($image_3, 0, 0, $color);
        imagecolortransparent($image_3, $color);
        //首先将背景画布采样copy到真彩色画布中，不会失真
        imagecopyresampled($image_3,$bg,0,0,0,0,imagesx($bg),imagesy($bg),imagesx($bg),imagesy($bg));

        if($nick['qiyong']==1){
            $nickname = $_W['fans']['nickname'];//微信昵称
            $color = $this->hex2rgb($nick['color']);
            $font_color = imagecolorallocate($image_3,$color['r'],$color['g'],$color['b']);
            $font = MODULE_ROOT."/fonts/Arial.ttf";  //写的文字用到的字体
            $str = mb_convert_encoding($nickname, "html-entities", "utf-8");//解决乱码问题
            imagettftext($image_3,$nick['size'],0,$nick['left'],$nick['top'],$font_color,$font,$str); //字体大小，旋转角度，x,y文字基点，字体的颜色，字体，内容
        }
        if($head['qiyong']==1){
            $headerimg = $this->Get_header_img();//微信头像
            $headerimg = imagecreatefromjpeg($headerimg);
            imagecopyresampled($image_3,$headerimg,$head['left'],$head['top'],0,0,$head['width'],$head['height'],imagesx($headerimg),imagesy($headerimg));  //左，上，右，下，新宽度，新高度，原宽度，原高度
        }
        if($qr['qiyong']==1){
            $erweimaurl = "http://qr.liantu.com/api.php?&w=".$qr['width']."&text=".urlencode($url);//二维码
            $erweimaurl = imagecreatefrompng($erweimaurl);
            imagecopymerge($image_3,$erweimaurl, $qr['left'],$qr['top'],0,0,imagesx($erweimaurl),imagesy($erweimaurl), 100);
        }

        $file_name = 'qrcode_'.$uniacid.'_'.$uid.'.jpg';
        $file_path = MODULE_ROOT.'/'.$uniacid.'/qrcode';

        if (!file_exists($file_path)) {
            load()->func('file');
            mkdirs($file_path);
        }
        $file = $file_path.'/'.$file_name;
        imagejpeg($image_3,$file);//保存到本地
        imagedestroy($image_3);
        return $this->Send_Img_Message($this->openid,$file,IMG_DAKA_PATH.$uniacid.'/qrcode/qrcode_'.$uniacid.'_'.$uid.'.jpg');

    }
    public function doMobileYaoqing() {
        global $_W,$_GPC;
        $today = date('Y-m-d',time());
        $uniacid =  $this->uniacid;
        $uid     = $_W['fans']['uid'];
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$uniacid);
        $other =json_decode($setting['other_setting'],true);
        $yajins=explode(",",$other['yajin']);
        $share =json_decode($setting['share_setting'],true);
        $yajin = pdo_fetch('SELECT id, uniacid,uid,yajin_state FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'"  AND apply_data ="' .$today .'"');
        //$is_fenxiao=0;//分销资格
       // if($yajin['yajin_state']==1){
            $url =  $_W['siteroot'].str_replace('./','app/',$this->createmobileurl('index')).'&fid='.$uid;
            $is_fenxiao=1;
            $is_file = 0;
            $file = IMG_DAKA_PATH.$uniacid.'/qrcode/qrcode_'.$uniacid.'_'.$uid.'.jpg';
            if (file_exists($file)) {
                $is_file=1;
            }
            include $this->template('yaoqing');
//        }else{
//            include $this->template('yaoqing');
//        }
    }

    public function doMobileCreateImage() {
        global $_W,$_GPC;
        $today = date('Y-m-d',time());
        $uniacid =  $this->uniacid;
        $uid     = $_W['fans']['uid'];
        $yajin = pdo_fetch('SELECT id, uniacid,uid,yajin_state FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'"  AND apply_data ="' .$today .'"');

        if(1==1){
            $url =  $_W['siteroot'].str_replace('./','app/',$this->createmobileurl('index')).'&fid='.$uid;
            $file = IMG_DAKA_PATH.$uniacid.'/qrcode/qrcode_'.$uniacid.'_'.$uid.'.jpg';
            $row = $this->CreateImage($url);
            if($row['State']==200){
                $row['State'] = 200;
                $row['Msg']=$file;
            }
            $row = json_encode($row);
        }else{
            $row['State'] = 201;
            $row['Msg']='你没有邀请资格';
            $row = json_encode($row);
        }
        echo $row;
        exit;
    }


    //增加修改邀请记录
    public function AddYaoqingRecord($fid){
        global $_W,$_GPC;
        $account_api = WeAccount::create();
        $follows = $account_api->fansQueryInfo($this->openid);
        $follow_satus = $follows['subscribe'];
        if($follow_satus!=1){
            $uniacid =  $_W['uniacid'];
            $cuid     = $_W['fans']['uid'];
            $openid =  $this->openid;
            $fid = intval($_GPC['fid']);
            $data = array(
                'uniacid' => $uniacid,
                'fuid'     => $fid,
                'cuid'  => $cuid,
                'openid'  => $openid,
                'yaoqing_data'  => date('Y-m-d h:i:s',time()),
                'follow_state'  => 0,
            );

            //判断该用户是否已经被邀请
            $user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yaoqing_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="'.$this->openid.'"');
            if(empty($user)){
                pdo_insert('zdaka_yaoqing_record', $data);
            }
            else {
                pdo_update('zdaka_yaoqing_record',$data,array('id' => $user['id']));
            }
        }
    }

    public function doMobileIndex() {
        // $this->CreateImage('13213');exit;
        //这个操作被定义用来呈现 功能封面
        //前台页面
        global $_W,$_GPC;
        $fid = intval($_GPC['fid']);
        load()->func('tpl');

        if (empty($_W['fans']['nickname'])) {
            mc_oauth_userinfo();
        }
        $uid = $_W['fans']['uid'];
        if($uid==0){
            message('请在微信中打开！', '', 'error');exit;
        }
        //var_dump($fid);exit;
        $follow_satus = 1;
        $uniacid =  $this->uniacid;
        if($_W['fans']['follow']!='1'){
            $account_api = WeAccount::create();
            $follows = $account_api->fansQueryInfo($this->openid);
            $follow_satus = $follows['subscribe'];
            if($follow_satus!='1'){
                if($fid!=0){
                    $yd_url = $this->createMobileUrl('yindao').'&fid='.$fid;
                }
                else{
                    $yd_url = $this->createMobileUrl('yindao');
                }
                header("location:$yd_url");
                exit;
            }
        }

        $nickname = $_W['fans']['nickname'];
        $openid =  $_W['fans']['openid'];
        $headimgurl = $this->Get_header_img();

        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $tomorrow = date("Y-m-d",strtotime("+1 day"));
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $user = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND openid ="' .$this->openid.'"');
        if($user['state']==1){
            message('你的数据异常请联系平台客户！', '', 'error');exit;
       }
        $fuser=  pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$this->uniacid. ' AND uid =' .$fid);
        if($fuser['fuid']!=0){
            $guid=$fuser['fuid'];
        }else{
            $guid=0;
        }
        if($user=='' && $uniacid !=''){
            $data = array(
                'guid'=>$guid,
                'fuid' => $fid,
                'uniacid' => $uniacid,
                'uid'     => $uid,
                'nickname'  => $nickname,
                'openid'  => $openid,
                'headimgurl'  => $headimgurl,
                'reg_time' => $time,
            );
            $rel = pdo_insert('zdaka_user', $data);
        }else{
            if($user['nickname'] != $nickname){
                $rel = pdo_update('zdaka_user',array('nickname' => $nickname),array('uniacid' => $uniacid,'openid' => $this->openid));
            }
            if($user['headimgurl'] != $headimgurl){
                $rel = pdo_update('zdaka_user',array('headimgurl' => $headimgurl),array('uniacid' => $uniacid,'openid' => $this->openid));
            }
            if($user['openid'] != $openid){
                $rel = pdo_update('zdaka_user',array('openid' => $openid),array('uniacid' => $uniacid,'openid' => $this->openid));
            }
        }

        //读取设置开始时间和结束时间
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$uniacid);
        $set =json_decode($setting['settings'],true);
        $starttime =  !empty($set['starttime'])?$set['starttime']:5;
        $endtime   =  !empty($set['endtime'])?$set['endtime']:8;
        $other =json_decode($setting['other_setting'],true);
        $yajins=explode(",",$other['yajin']);
        $zyajins=explode(",",$other['zyajin']?$other['zyajin']:$other['yajin']);
        $images=$other['images']?explode(",",$other['images']):"";
        $share =json_decode($setting['share_setting'],true);
        $today_5 = strtotime($today)+3600*$starttime;
        $today_8 = strtotime($today)+3600*$endtime;
        $djs=0;
        if(strtotime($time)<=$today_5){
            $djs=$today_5-time();
        }
        if(strtotime($time)>=$today_8){
            $djs= $today_5+86400-time();
        }
        $upstate=pdo_getall('zdaka_yajin_record',array('uniacid'=>$uniacid,'yajin_state'=>1));
        foreach ($upstate as $k=>$v){
            if( strtotime($upstate[$k]['apply_data'])<strtotime($yesterday)){
                pdo_update('zdaka_yajin_record',array('yajin_state'=>0,'demo'=>'未打卡'),array('id'=>$v['id']));
            }
        }
        // 判断押金是否可用
        $is_tiao='0';
        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE  uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'" and yajin_state= 1');
        if(!empty($yajin)){
            if(strtotime($time)>=$today_5 && strtotime($time)<=$today_8&&$yajin['apply_data']==$yesterday){
                $is_tiao='2';
            }elseif(strtotime($time)<=$today_5){
                $is_tiao='3';
            }else{
                $is_tiao='1';
            }
        }else{
            $is_tiao='0';
        }
        if($this->fstate==1){
            if(strtotime($time)>$today_8){
                $file_name = MODULE_ROOT.'/'.$_W['uniacid'].'/record/'.$today.'.rlc';
                if(!file_exists($file_name)){
                    $is_tiao='4';
                }

            }
        }



        //判断该用户是否为被邀请用户，若为被邀请用户并且已关注，则修改关注状态
//        $yq_user = pdo_fetch('SELECT id,uniacid,fuid,follow_state,fllow_count FROM ' . tablename('zdaka_yaoqing_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="'.$openid.'"');
//        if($yq_user){
//            if($follow_satus=='1' && $yq_user['follow_state']==0){
//                //查询邀请人的押金状态
//                $yj_yaoqing = pdo_fetch('SELECT `id`,`yajin_state`,yajin_money FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND uid ='.$yq_user['fuid'].' order by yajin_data,id desc limit 1');
//                pdo_update('zdaka_yaoqing_record',array('follow_state'=>1,'fllow_count +='=>1),array('id' => $yq_user['id']));
//                if($yj_yaoqing['yajin_state']=='1' && $yj_yaoqing['yajin_money']>=$this->zd_yj && $yj_yaoqing['fllow_count']==0){
//                    //如果押金可用，增加打卡奖金分配份数
//                    pdo_update('zdaka_yajin_record',array('bonus_num +='=>1),array('uniacid' => $uniacid,'uid' => $yq_user['fuid']));
//                }
//            }
//        }

        //查询可用押金数量
        if(strtotime($time)<$today_8){
            $yajin_list =  pdo_fetchall('SELECT * FROM '. tablename('zdaka_yajin_record').' WHERE apply_data="'.$yesterday.'" AND  uniacid ='.$uniacid.'  AND yajin_state=1 order by  yajin_data desc');
        }else{
            $yajin_list =  pdo_fetchall('SELECT * FROM '. tablename('zdaka_yajin_record').' WHERE apply_data="'.$today.'" AND  uniacid ='.$uniacid.'  AND yajin_state=1 order by yajin_data desc ');
        }
        $total_money=0;
        foreach ($yajin_list as $k=>$v){
            $total_money+= $v['yajin_money'];
        }
        //查询当天打卡成功和失败数量
        if(strtotime($time)>$today_8){
           // pdo_update('zdaka_yajin_record',array('Invaliddate' => $today),array('uniacid' => $uniacid,'yajin_state' => 1,'daka_date !=' => $today,'apply_data <'=>date('Y-m-d H:i:s',$today_8)));
            $success_total = pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$today.'"');//成功人数
            $fail_total =  pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_yajin_record').' WHERE uniacid ='.$uniacid.' AND Invaliddate ="'.$today.'"');//失败人数

        }else{

            $success_total = pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$yesterday.'"');//成功人数
            $fail_total =  pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_yajin_record').' WHERE uniacid ='.$uniacid.' AND Invaliddate ="'.$yesterday.'"');//失败人数
        }
        //查询早起之星
        if(strtotime($time)>$today_8){
            $zqzx = pdo_fetch('SELECT * FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$today.'" order by daka_datatime  limit 1');//成功人数
        }else{
            $zqzx = pdo_fetch('SELECT * FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$yesterday.'" order by daka_datatime  limit 1');//成功人数
        }
        //查询毅力之星
        $ylzx = pdo_fetch('SELECT * FROM '. tablename('zdaka_total_record').' WHERE uniacid ='.$uniacid.' order by user_total_score desc  ,last_sign_time asc limit 1');

        //查询手气之星
        $sqzx = pdo_fetch('SELECT * FROM '. tablename('zdaka_total_record').' WHERE uniacid ='.$uniacid.' order by user_total_money desc  ,last_sign_time asc limit 1');

        //超过打卡时间访问页面执行打卡金发放
		//@TODO
        if($this->fstate==0){
            if(strtotime($time)>$today_8){
                $file_name = MODULE_ROOT.'/'.$_W['uniacid'].'/record/'.$today.'.rlc';
                if(!file_exists($file_name)){
                	//增加文件锁解决高并发 非阻塞模式如果其他进程已经加锁文件,当前进程不会等其他进程解锁文件,直接返回,也就是直接忽略加锁的代码到关闭文件那块
                	$fp_name = MODULE_ROOT.'/'.$_W['uniacid'].'/record/lock.txt';                	
					if(!file_exists($fp_name)){
						$file_path = MODULE_ROOT.'/'.$this->uniacid.'/record';
				        if (!file_exists($file_path)) {
				            load()->func('file');
				            mkdirs($file_path);
				        }
						file_put_contents($fp_name,"文件锁",FILE_APPEND);
					}
					$lock = fopen($fp_name, "r");
					if(flock($lock,LOCK_EX | LOCK_NB)){
						$this->DKsend($lock);
					}
					//关闭文件
					fclose($lock);							
                }
            }
        }		
		
        $nostate   =  !empty($set['nostate'])?$set['nostate']:0;
        $notice=pdo_fetchall('SELECT * FROM '. tablename('zdaka_notice_record').' WHERE acid ='.$uniacid.'  and state=0 ');
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');
        $daymoney=pdo_get('zdaka_daymoney_record',array('acid'=>$this->uniacid,'date'=>$tomorrow));
        include $this->template('index');
    }

    //测试打卡奖励金发放
    public function doMobileTestsend(){
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $time = strtotime(date('Y-m-d H:i:s'));
        $today = strtotime(date('Y-m-d'));

        if($uniacid==''){
            $uniacid =  $_W['uniacid'];
        }

        //查询商户设置
        $setting = pdo_fetch("select * from ".tablename('zdaka_config')." where uniacid = {$uniacid}");
        $set =  json_decode($setting['settings'],true);
        $openid  = $set['user_openid'];
        $pars = array();

        $pars['mch_appid'] =$set['appid'];

        $pars['mchid'] = $set['mch_id'];

        //产生随机字符串
        $pars['nonce_str'] = $this->createNoncestr();

        // 商户订单号
        $pars['partner_trade_no'] = $uniacid.$time;
        // 用户openid
        $pars['openid'] =$openid;
        // 校验用户姓名选项
        $pars['check_name'] = "NO_CHECK";
        // 企业付款金额  单位为分
        $pars['amount'] =100;
        // 企业付款描述信息
        $pars['desc'] = '测试打卡奖励金发放';
        // 调用接口的机器IP地址  自定义
        $pars['spbill_create_ip'] =$_SERVER["REMOTE_ADDR"];
        //生成签名
        $pars['sign'] =$this->getSign($pars);

        // echo "<pre>";
        // print_r($pars);exit;

        $xml = $this->createXml($pars);

        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';


        $response = $this->curl_post_ssl($url, $xml);

        $data = simplexml_load_string($response, null, LIBXML_NOCDATA);
        $jsonStr = json_encode($data);
        $jsonArray = json_decode($jsonStr,true);
        //微信交易单号
        $jiaoyi_number = $jsonArray['payment_no'];
        $jiaoyi_time = strtotime($jsonArray['payment_time']);

        if($jsonArray['result_code']=='SUCCESS'){
            message('发放成功！', $this->createMobileUrl('index'), 'success');

        }else{
            message('发放失败！'.$jsonArray['err_code_des'], $this->createMobileUrl('index'), 'error');
        }

    }


    public function doMobileSign() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //打卡
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $openid =  $_W['fans']['openid'];
        $headimgurl =  $this->Get_header_img(); //头像
        $nickname = $_W['fans']['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        //判断是是否存在可用打卡押金
        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND apply_data ="' .$yesterday .'" AND openid ="' .$this->openid .'"  and yajin_state = 1');
        if(empty($yajin)){
            $row['Msg']='昨日未交保证金';
            $row = json_encode($row);
            echo $row;
            exit;
        }
        //读取设置开始时间和结束时间
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$uniacid);
        $set =json_decode($setting['settings'],true);
        $starttime =  !empty($set['starttime'])?$set['starttime']:5;
        $endtime   =  !empty($set['endtime'])?$set['endtime']:8;
        $today_5 = strtotime($today)+3600*$starttime;
        $today_8 = strtotime($today)+3600*$endtime;
        //查询是今天否打卡，如果没有打卡，执行打卡
        $sql = 'SELECT *  FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$openid. '" AND daka_date = "'.$today.'"';
        $qian = pdo_fetch($sql);
        if($qian){
            $row['State'] = 0;
            $row['Msg']='今日已打卡！';
            $row = json_encode($row);
            echo $row;
            exit;
        }else if(strtotime($time)>=$today_5 && strtotime($time)<=$today_8){
            //插入打卡记录
            $post = array(
                'uniacid' => $this->uniacid,
                'uid' =>  $_W['fans']['uid'],
                'openid' => $_W['fans']['openid'],
                'nickname' => $_W['fans']['nickname'],
                'headimgurl' =>$this->Get_header_img(),
                'daka_date' => $today,
                'daka_datatime' => $time,
                'huikuan_date' => $yajin['huikuan_date'],
                'bonus_num' => $yajin['yajin_money'],
                'yid' => $yajin['id'],
            );
            pdo_insert('zdaka_sign_record', $post);
            //更改押金表中打卡状态为已打卡
            pdo_update('zdaka_yajin_record',array('is_daka' => 1,'daka_date'=>$today),array('uniacid' => $uniacid,'yajin_state' => 1,'openid'=>$this->openid));

            //查询记录天数表中是否有记录
            $sql = 'SELECT *  FROM ' . tablename('zdaka_total_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid.'"';
            $rel  = pdo_fetchall($sql);
            if($rel){
                //查询昨天是否打卡，如果打卡打卡填上累加，如果没打卡，打卡天数从新计算
                $sql1 = 'SELECT *  FROM ' . tablename('zdaka_total_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid. '" AND last_sign_date = "'.$yesterday.'"';
                $result = pdo_fetchall($sql1);
                if($result){
                    $data = array(
                        'uniacid' => $this->uniacid,
                        'uid' =>  $_W['fans']['uid'],
                        'openid' =>  $_W['fans']['openid'],
                        'headimgurl' =>  $this->Get_header_img(),
                        'nickname' => $_W['fans']['nickname'],
                        'last_sign_date' => $today,
                        'last_sign_time' => $time,
                        'user_total_score' => $result['0']['user_total_score']+1,
                    );
                    pdo_update('zdaka_total_record', $data,array('uniacid' => $this->uniacid, 'openid' => $this->openid));
                }
                else{
                    $data = array(
                        'uniacid' => $this->uniacid,
                        'uid' =>  $_W['fans']['uid'],
                        'openid' =>  $_W['fans']['openid'],
                        'headimgurl' =>  $this->Get_header_img(),
                        'nickname' => $_W['fans']['nickname'],
                        'last_sign_date' => $today,
                        'last_sign_time' => $time,
                        'user_total_score' => 1,
                    );
                    pdo_update('zdaka_total_record', $data,array('uniacid' => $this->uniacid, 'openid' => $this->openid));
                }
            }
            else{
                $data = array(
                    'uniacid' => $this->uniacid,
                    'uid' =>  $_W['fans']['uid'],
                    'openid' =>  $_W['fans']['openid'],
                    'headimgurl' => $this->Get_header_img(),
                    'nickname' => $_W['fans']['nickname'],
                    'last_sign_date' => $today,
                    'last_sign_time' => $time,
                    'user_total_score' =>1,
                );
                pdo_insert('zdaka_total_record', $data);
            }
            $row['State'] = 200;
            $row['Msg']='打卡成功！';
            $row = json_encode($row);
            echo $row;
        }else{
            $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND apply_data ="' .$yesterday .'" AND openid ="' .$this->openid .'"  order by yajin_data,id desc limit 1');
            pdo_update('zdaka_yajin_record', array('yajin_state' =>0,'demo'=>$today.'打卡失败'),array('id'=>$yajin['id']));

            $row['State'] = 202;
            $row['Msg']='每天打卡时间为早'.$today_8.':00-'.$endtime.':00哦！';
            $row = json_encode($row);
            echo $row;
        }
    }




    public function doMobileTiaozhanrecord() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //挑战记录
        $uniacid =  $this->uniacid;
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');
        include $this->template('tiaozhan_record');
    }

    public function doMobileRanking() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //挑战记录
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $fans = mc_oauth_userinfo();
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $today_8 = strtotime($today)+3600*$this->dk_endtime;
        //查询当天打卡成功和失败数量
        if(strtotime($time)>$this->today_end){
            $success_total = pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$today.'"');//成功人数
            $fail_total =  pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_yajin_record').' WHERE uniacid ='.$uniacid.' AND Invaliddate ="'.$today.'"');//失败人数
        }else{
            $success_total = pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$yesterday.'"');//成功人数
            $fail_total =  pdo_fetchcolumn('SELECT COUNT(id) FROM '. tablename('zdaka_yajin_record').' WHERE uniacid ='.$uniacid.' AND Invaliddate ="'.$yesterday.'"');//失败人数
        }


        //查询早起之星
        if(strtotime($time)>$today_8){
            $zqzx = pdo_fetch('SELECT * FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$today.'"');//成功人数
        }else{
            $zqzx = pdo_fetch('SELECT * FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$yesterday.'"');//成功人数
        }

        //查询毅力之星
        $ylzx = pdo_fetch('SELECT * FROM '. tablename('zdaka_total_record').' WHERE uniacid ='.$uniacid.' order by user_total_score desc ,last_sign_time asc limit 1');

        //查询手气之星
        $sqzx = pdo_fetch('SELECT * FROM '. tablename('zdaka_total_record').' WHERE uniacid ='.$uniacid.' order by user_total_money desc ,last_sign_time asc limit 1');
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');

        include $this->template('ranking');
    }

    public function doMobileRule() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //挑战记录
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];

        //读取设置开始时间和结束时间
        $setting = pdo_fetch('SELECT * FROM ' . tablename('zdaka_config') . ' WHERE uniacid ='.$uniacid);
        $set =json_decode($setting['settings'],true);
        $others =json_decode($setting['other_setting'],true);
        $starttime =  !empty($set['starttime'])?$set['starttime']:5;
        $endtime   =  !empty($set['endtime'])?$set['endtime']:8;
        include $this->template('rule');
    }
    public function doMobileGetrank() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //挑战记录
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $value = trim($_GPC['value']);
        $array = array();
        if($value=='Morning'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$uniacid. ' AND daka_date ="' .$today. '" order by daka_datatime  limit 20');
            foreach($rank_record as $k=>$item){
                $row['id'] = $k+1;;
                $row['ss'] = $k;
                $row['nickname'] = $item['nickname'];
                $item['headimgurl'] = '' ? IMG_DAKA_PATH.'images/moren.jpg' : $item['headimgurl'];
                $row['headimgurl'] = $item['headimgurl'];
                $row['text'] = '打卡'.date('H:i',strtotime($item['daka_datatime']));
                $array[$row['id']] = $row;
            }
            $array = json_encode($array);
            echo $array;
            exit;
        }
        if($value=='Luck'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_total_record') . ' WHERE uniacid ='.$uniacid. ' order by user_total_money desc ,last_sign_time asc limit  20');
            foreach($rank_record as $k=>$item){
                $row['id'] = $k+1;
                $row['nickname'] = $item['nickname'];
                $item['headimgurl'] = '' ? IMG_DAKA_PATH.'images/moren.jpg' : $item['headimgurl'];
                $row['headimgurl'] = $item['headimgurl'];
                $row['text'] = $item['user_total_money'].'元';
                $array[$row['id']] = $row;
            }

            $array = json_encode($array);
            echo $array;
            exit;
        }
        if($value=='Will'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_total_record') . ' WHERE uniacid ='.$uniacid. ' order by user_total_score desc ,last_sign_time asc limit 20' );
            foreach($rank_record as $k=>$item){
                $row['id'] = $k+1;
                $row['nickname'] = $item['nickname'];
                $item['headimgurl'] = '' ? IMG_DAKA_PATH.'images/moren.jpg' : $item['headimgurl'];
                $row['headimgurl'] = $item['headimgurl'];
                $row['text'] = '打卡'.$item['user_total_score'].'次';
                $array[$row['id']] = $row;
            }
            $array = json_encode($array);
            echo $array;
            exit;
        }
    }

    public function doMobileYqhy() {
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $acid=$this->uniacid;
        $zuijing = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND fuid =' .$uid.' order by reg_time desc limit 0, 1' );
        $zuiduo = pdo_fetch('SELECT sum(money) as money ,zuid FROM ' . tablename('zdaka_yqsy_record') . ' WHERE fuid ='.$uid.' group by zuid order by sum(money) desc limit 0, 1 ' );
        $zuiduo1=pdo_get('zdaka_user',array('uid'=>$zuiduo['zuid']));
        $cishu = pdo_fetch('SELECT count(id) as cishu ,zuid FROM ' . tablename('zdaka_yqsy_record') . ' WHERE fuid ='.$uid.' group by zuid order by count(id) desc limit 0, 1 ' );
        $cishu1=pdo_get('zdaka_user',array('uid'=>$cishu['zuid']));
        //var_dump( $zuiduo1);exit;
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');
        include $this->template('yqlb');
    }
    public function doMobileDkmx() {
        //挑战记录
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $fans = mc_oauth_userinfo();
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $today_8 = strtotime($today)+3600*$this->dk_endtime;
        //查询当天打卡成功和失败数量
        if(strtotime($time)>$this->today_end){
            $success_total = pdo_fetchall('SELECT * FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$today.'"');//成功人数
            $fail_total =  pdo_fetchall('SELECT * FROM '. tablename('zdaka_yajin_record').' WHERE uniacid ='.$uniacid.' AND Invaliddate ="'.$today.'"');//失败人数
        }else{
            $success_total = pdo_fetchall('SELECT * FROM '. tablename('zdaka_sign_record').' WHERE uniacid ='.$uniacid.' AND daka_date ="'.$yesterday.'"');//成功人数
            $fail_total =  pdo_fetchall('SELECT * FROM '. tablename('zdaka_yajin_record').' WHERE uniacid ='.$uniacid.' AND Invaliddate ="'.$yesterday.'"');//失败人数
        }

        //查询早起之星
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');
        include $this->template('dkmx');
    }
    public function doMobileYqlb() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //好友列表
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $value = trim($_GPC['value']);
        $array = array();
        if($value=='lb'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND fuid =' .$uid .' order by reg_time desc limit 0, 20');
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['nickname'] =  mb_substr($item['nickname'], 0, 12,'utf-8');

            }
            echo json_encode($rank_record);
            exit;
        }
        if($value=='money'){
            $rank_record = pdo_fetchall('SELECT sum(money) as money ,zuid FROM ' . tablename('zdaka_yqsy_record') . ' WHERE fuid ='.$uid.' group by zuid ' .' order by sum(money) desc limit 0, 20'  );
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['money'] = round($item['money'],2);
                $rank_record[$k]['user'] = pdo_get('zdaka_user',array('uid'=>$item['zuid']));
            }
            echo json_encode($rank_record);
            exit;
        }
        if($value=='mx'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yqsy_record') . ' WHERE acid ='.$uniacid. ' AND fuid =' .$uid .' order by date desc limit 0, 20' );
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['user'] = pdo_get('zdaka_user',array('uid'=>$item['zuid']));
                $rank_record[$k]['date'] = date('m-d H:s',strtotime($item['date']));
            }
            echo json_encode($rank_record);
            exit;
        }
    }
    public function doMobileJrmx() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //好友列表
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $yesterday = date("Y-m-d",strtotime("-1 day"));
        $value = trim($_GPC['value']);
        $array = array();
        if($value=='Luck'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_grant_record') . ' WHERE uniacid ='.$uniacid. ' AND grant_date ="' .$today .'" order by grant_money desc limit 0, 10');
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['sss'] =$item['grant_money']."元";
            }
            echo json_encode($rank_record);
            exit;
        }
        if($value=='Morning'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$uniacid. ' AND daka_date ="' .$today .'"  order by daka_datatime   limit 0, 10'  );
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['sss'] ="打卡".date('H:i:s',strtotime($item['daka_datatime']));
            }
            echo json_encode($rank_record);
            exit;
        }
        if($value=='Will'){
            $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND yajin_state = 1  order by yajin_data  limit 0, 10' );
            foreach($rank_record as $k=>$item){
                $rank_record[$k]['sss'] =((strtotime($today)-strtotime(date('Y-m-d',strtotime($item['yajin_data']))))/86400)."天";
            }
            echo json_encode($rank_record);
            exit;
        }
    }

    public function doMobilePayrecord() {

        //这个操作被定义用来呈现 微站快捷功能导航
        //支付明细
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];

        $fans = mc_oauth_userinfo();
        $pay_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid. '" order by yajin_data desc');

        $user_info = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid.'"' );

        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE yajin_state=1 AND uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'"  order by yajin_data,id desc limit 1');

        $total_day = $this->Get_total_day();
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');

        include $this->template('pay_record');
    }

    public function doMobileSignrecord() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //打卡记录
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];

        $fans = mc_oauth_userinfo();

        $sign_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_sign_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid. '" order by daka_datatime desc');

        $user_info = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid. '"' );

        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE yajin_state=1 AND uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'"  order by yajin_data,id desc limit 1');
        $total_day = $this->Get_total_day();
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');

        include $this->template('sign_record');
    }
    public function doMobileBonusrecord() {
        //这个操作被定义用来呈现 功能封面
        //收益记录
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];
        $fans = mc_oauth_userinfo();

        $bonus_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_grant_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid. '" order by grant_data desc');

        $user_info = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid. '"' );

        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE yajin_state=1 AND uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'"  order by yajin_data,id desc limit 1');

        $total_day = $this->Get_total_day();
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');

        include $this->template('bonus_record');
    }
    public function doMobileTixianrecord() {
        ////这个操作被定义用来呈现 微站快捷功能导航
        //提现记录
        global $_W,$_GPC;
        $uid = $_W['fans']['uid'];
        $uniacid =  $this->uniacid;
        $nickname = $_W['fans']['nickname'];
        $fans = mc_oauth_userinfo();
        $user_info = pdo_fetch('SELECT * FROM ' . tablename('zdaka_user') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid.'"' );

        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE yajin_state=1 AND uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'"  order by yajin_data,id desc limit 1');

        $rank_record = pdo_fetchall('SELECT * FROM ' . tablename('zdaka_tixian_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid. '" order by tixian_data desc');
        $total_day = $this->Get_total_day();
        $blist=pdo_fetchall('SELECT * FROM '. tablename('zdaka_list').' WHERE acid ='.$uniacid.'  order by xuhao limit 0,4 ');

        include $this->template('tixian_record');
    }
    public function doMobilePay()
    {
        //这个操作被定义用来呈现 微站快捷功能导航
        //调用支付
        global $_W, $_GPC;
//		if($this->zd_yj<1){
//			message('暂未设置押金金额！', $this->createMobileUrl('index'), 'error');
//		}
        $uid = $_W['fans']['uid'];
        $openid = $_W['fans']['openid'];
        $uniacid = $this->uniacid;
        //构造支付请求中的参数
        $time = date('Y-m-d H:i:s',time());
        $params = array(
            'tid' => $uid.time(),      //充值模块中的订单号，此号码用于业务模块中区分订单，交易的识别码
            'ordersn' => $uid.time(),  //收银台中显示的订单号
            'title' => '挑战金',          //收银台中显示的标题
            'fee' => $_GPC['money'],      //收银台中显示需要支付的金额,只能大于 0
            'user' => $uid,     //付款用户, 付款的用户名(选填项)
            'openid' => $openid,
            'serial' => time() . rand(0000, 9999) + $uid,
            'state' => 0,
            'zstate' => $_GPC['zstate'],
            'uniacid' => $this->uniacid,
            'time'=>$time
        );

        //$yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'"  order by yajin_data,id desc limit 1');
        //var_dump($this->zhouqi);exit;
        $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE uniacid =' . $uniacid . ' AND openid ="' . $this->openid . '" AND yajin_state = 1 ');
        //var_dump($this->openid);exit;
        if (empty($yajin)) {
            $res = pdo_insert('zdaka_pay_record', $params);
            if ($res && $_GPC['money'] != 0) {
                $this->pay($params);
            } else {
                message('请选择金额！', $this->createMobileUrl('index'), 'error');
            }
            //调用pay方法
        } else {
            if($this->fdje !=0){
                if(($yajin['yajin_money']+$_GPC['money'])>$this->fdje){
                    message('大于封顶金额：'.$this->fdje, $this->createMobileUrl('index'), 'error');exit;
                }
            }

            $res = pdo_insert('zdaka_pay_record', $params);
            if ($res && $_GPC['money'] != 0) {
                $this->pay($params);
            } else {
                message('请选择金额！', $this->createMobileUrl('index'), 'error');
            }
        }
    }
    public function payResult($params) {
        //这个操作被定义用来呈现 微站快捷功能导航
        //支付后触发这个方法
        //var_dump($params);exit;
        global $_W,$_GPC;
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $huikuan=time()+3600*24*($this->zhouqi);
        $huikuan_data = date('Y-m-d',$huikuan);
        $uniacid =  $params['uniacid']; //公众号id
        $uid = $params['user'];  //用户uid

        //一些业务代码
        //根据参数params中的result来判断支付是否成功

        //因为支付完成通知有两种方式 notify，return,notify为后台通知,return为前台通知，需要给用户展示提示信息
        //return做为通知是不稳定的，用户很可能直接关闭页面，所以状态变更以notify为准
        //如果消息是用户直接返回（非通知），则提示一个付款成功
        if ($params['result'] == 'success' && $params['from'] == 'notify') {
            //预约打卡
            // $this->logResult($params);
            pdo_update('zdaka_pay_record', array('state' => 1), array('tid' => $params['tid']));
            $gres= pdo_get('zdaka_pay_record', array('tid' => $params['tid'],'state' => 1));
            if($gres['zstate']==1){
               $res= pdo_update('zdaka_yajin_record', array('yajin_money +=' => $params['fee'], 'bonus_num +=' => $params['fee']), array('openid' => $gres['openid'],'yajin_state'=>1));
               if($res){
                   message('追加成功！', $this->createMobileUrl('index'), 'success');  exit;
               }else{
                   message('加入失败！', $this->createMobileUrl('index'), 'error');  exit;
               }

            }
            $user = pdo_get('zdaka_user', array('openid' => $gres['openid']));

             if($this->ysstate==1){
                  $a=pdo_get('zdaka_yajin_record',array('openid'=>$gres['openid']));
                 if(!$a && $user['fuid']!=0){
                     if($user['fuid']!=0){
                         $fuser = pdo_update('zdaka_user', array('money +=' =>$params['fee']*$this->bili/100),array('uid'=>$user['fuid']));
                         $data1=array(
                             'fuid'=>$user['fuid'],
                             'zuid'=>$user['uid'],
                             'money'=>$params['fee']*$this->bili/100,
                             'date'=>$time,
                             'acid'=>$uniacid,
                         );
                         pdo_insert('zdaka_yqsy_record', $data1);
                         $data2 = array(
                             'uniacid' => $this->uniacid,
                             'money'     => $params['fee']*$this->bili/100,
                             'date' => $today,
                             'state' => 1,
                             'demo' => $today.'邀请支出'
                         );
                         pdo_insert('zdaka_yinli_record', $data2);
                     }
                 }
             }else{
                 if($user['fuid']!=0){
                     $fuser = pdo_update('zdaka_user', array('money +=' =>$params['fee']*$this->bili/100),array('uid'=>$user['fuid']));
                     $data1=array(
                         'fuid'=>$user['fuid'],
                         'zuid'=>$user['uid'],
                         'money'=>$params['fee']*$this->bili/100,
                         'date'=>$time,
                         'acid'=>$uniacid,
                     );
                     pdo_insert('zdaka_yqsy_record', $data1);
                     $data2 = array(
                         'uniacid' => $this->uniacid,
                         'money'     => $params['fee']*$this->bili/100,
                         'date' => $today,
                         'state' => 1,
                         'demo' => $today.'邀请支出'
                     );
                     pdo_insert('zdaka_yinli_record', $data2);
                 }
             }

            $data = array(
                'uniacid' => $uniacid,
                'uid' => $user['uid'],
                'openid' => $user['openid'],
                'headimgurl' => $user['headimgurl'],
                'nickname' => $user['nickname'],
                'yajin_money' => $params['fee'],
                'yajin_data' => $time,
                'apply_data' => $today,
                'yajin_state' => 1,
                'demo' => '支付挑战金成功',
                'is_daka' => 0,
                'huikuan_date' => $huikuan_data,
                'bonus_num' => $params['fee']
            );
            $rel = pdo_insert('zdaka_yajin_record', $data);


        }
        if ($params['from'] == 'return') {
            if ($params['result'] == 'success') {
                message('加入挑战成功！', $this->createMobileUrl('index'), 'success');
            } else {
                message('加入失败！', $this->createMobileUrl('index'), 'success');
            }
        }
    }

    public function doMobileypay() {
        //这个操作被定义用来呈现 微站快捷功能导航
        //支付后触发这个方法
        //var_dump($params);exit;
        global $_W,$_GPC;
        $time = date('Y-m-d H:i:s',time());
        $today = date('Y-m-d',time());
        $huikuan=time()+3600*24*($this->zhouqi);
        $huikuan_data = date('Y-m-d',$huikuan);
        $uniacid =  $this->uniacid; //公众号id
        $uid = $_W['fans']['uid'];;  //用户uid

            $res=pdo_update('zdaka_user', array('money -=' => $_GPC['money']), array('openid' => $this->openid,'uniacid'=> $uniacid));
            $yajin = pdo_fetch('SELECT * FROM ' . tablename('zdaka_yajin_record') . ' WHERE  uniacid ='.$uniacid. ' AND openid ="' .$this->openid .'" and yajin_state= 1');
            if($res){
                if($_GPC['zstate']==1&&$yajin){
                    $res1= pdo_update('zdaka_yajin_record', array('yajin_money +=' => $_GPC['money'], 'bonus_num +=' =>  $_GPC['money']), array('openid' => $this->openid,'yajin_state'=>1));
                    if($res1){
                        message('追加成功！', $this->createMobileUrl('index'), 'success');  exit;
                    }else{
                        message('加入失败！', $this->createMobileUrl('index'), 'error');  exit;
                    }

                }else{
                    $user = pdo_get('zdaka_user', array('openid' => $this->openid));
                    $data = array(
                        'uniacid' => $uniacid,
                        'uid' => $user['uid'],
                        'openid' => $user['openid'],
                        'headimgurl' => $user['headimgurl'],
                        'nickname' => $user['nickname'],
                        'yajin_money' => $_GPC['money'],
                        'yajin_data' => $time,
                        'apply_data' => $today,
                        'yajin_state' => 1,
                        'demo' => '支付挑战金成功',
                        'is_daka' => 0,
                        'huikuan_date' => $huikuan_data,
                        'bonus_num' =>  $_GPC['money'],
                    );
                    if($yajin){
                        $rel= pdo_update('zdaka_yajin_record', array('yajin_money +=' => $_GPC['money'], 'bonus_num +=' =>  $_GPC['money']), array('openid' => $this->openid,'yajin_state'=>1));
                    }else{
                        $rel = pdo_insert('zdaka_yajin_record', $data);
                    }
                    if($rel){
                        message('加入挑战成功！', $this->createMobileUrl('index'), 'success');
                    }
                }

            }



    }




    public function logResult($params) {
        global $_W,$_GPC;
        $file_name = MODULE_ROOT.'/pay_log.txt';
        $file_path = MODULE_ROOT;
        if (!file_exists($file_path)) {
            load()->func('file');
            mkdirs($file_path);
        }
        file_put_contents($file_name,$params,FILE_APPEND);
    }

    public function wtw_request($url,$data=null){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        if($data != null){
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 300); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $info = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            //echo 'Errno:'.curl_getinfo($curl);//捕抓异常
            //dump(curl_getinfo($curl));
        }
        return $info;
    }


    public function templetemsgdk($openid,$templateid,$start,$end,$nickname,$phone){
        //获取ACCESS_TOKEN
        /*string(86)"*****"
        * string(45)"{"errcode":0,"errmsg":"ok","msgid":201652404}"
       */
        global $_W,$_GPC;
        $account_api = WeAccount::create();
        $account_api->clearAccessToken();
        $token = $account_api->getAccessToken();
        $msg_url="http://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
        $time = date("Y-m-d H:i:s",time());
        $url =$_W['siteroot'].$this->createMobileUrl('Index'); ////这个链接是点击图文 跳转的链接,换行只能用n 不能用<Br/>
        ////请求包为一个json：
        $msg_json= '{
            "touser":"'.$openid.'",
            "template_id":"'.$templateid.'",
            "url":"'.$url.'",
            "topcolor":"#FF0000",
            "data":{
                "first":{
                "value":"'.$time.'",
                "color":"#FF0000"
                },
                "keyword1":{
                "value":"'.$start.'",
                "color":"#000000"
                },
                "keyword2":{
                "value":"'.$end.'",
                "color":"#000000"
                },           
                "keyword3":{
                "value":"'.$time.'",
                "color":"#000000"
                },
                "keyword4":{
                "value":"'.$nickname.'",
                "color":"#000000"
                },
                "keyword5":{
                "value":"'.$phone.'",
                "color":"#000000"
                },
            }
        }';
        //var_dump($msg_json);exit;
        $result = $this->wtw_request($msg_url,$msg_json);

        return $result;
    }
     public function doMobileInfo(){
         global $_W,$_GPC;
         $res=pdo_get('zdaka_notice_record',array('id'=>$_GPC['nid'],'acid'=>$this->uniacid));
         include $this->template('info');
    }

}